package com.cn.ycy.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 不在转发请求到uri，网关直接 返回响应体
 */
@Component
public class ResponseGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

  private static Logger logger = LoggerFactory.getLogger(ResponseGatewayFilterFactory.class);

  @Override
  public GatewayFilter apply(NameValueConfig config) {
    return new GatewayFilter() {
      @Override
      public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info(" add token name {} ,value {}", config.getName(), config.getValue());
        //chain 不传递了 到我这断了
        return firstCheck(exchange,"我是网关");
      }
    };
  }


  /**
   * 直接响应客户端 message
   */
  public Mono<Void> firstCheck(ServerWebExchange exchange, String message) {
    return Mono.defer(() -> {
      byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
      ServerHttpResponse response = exchange.getResponse();
      DataBuffer buffer = response.bufferFactory().wrap(bytes);
      return response.writeWith(Flux.just(buffer));
    });
  }


}
